<template>
    <div class="e-form">
        <BillTop title="租赁计划变更编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
             <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="计划明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData" label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划编号：">
                                            <span>{{ formData.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更编号：">
                                            <span>{{ formData.changeBillNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="变更日期：">
                                            <span>{{ formData.billDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="币种：">
                                            <span>{{ formData.currency }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="原金额（元）：">
                                            <span>{{ formData.totalCost }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更后金额（元）：">
                                            <span>{{ formData.changeTotalCost }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ statusLable(formData.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁类型：">
                                            <span>{{formData.leaseType ? leaseTypeList[formData.leaseType].label :''}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更期数：">
                                            <span>{{formData.number}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{ formData.baseCurName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12" v-if="formData.leaseType == '2'">
                                        <el-form-item label="传输财务共享：">
                                            <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.share)}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item  label="租赁说明：">
                                            <el-input type="textarea" v-model="formData.remarks" placeholder="请输入内容"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{formData.rmbRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">计划明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button  class="btn-greenYellow" @click="selectEquip" v-if="leaseTypeList[formData.leaseType].label=='临租'">选择基础库设备</el-button>
                                        <el-button  class="btn-greenYellow" @click="selectConfigEquip" v-else>选择配置计划设备</el-button>
                                        <el-button  class="btn-delete"  @click="deletePlanList " v-if="isBatch">批量删除</el-button>
                                        <el-button  @click="cancelDelete" v-if="isBatch">取消删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{batch}}</span>
                                    </div>
                                </div>
                                <div class="right">
                                    <div class="squarecolor">
                                        <div class="color colorAdd"></div>
                                        <span>新增</span>
                                    </div>
                                    <div class="squarecolor item">
                                        <div class="color colorUpdate"></div>
                                        <span>修改</span>
                                    </div>
                                    <div class="squarecolor">
                                        <div class="color colorDel"></div>
                                        <span>删除</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="planConfigurationDtlListCopy"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                :row-class-name="tableRowClass"
                                v-sortTable="{ 'tableData': planConfigurationDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column  fixed type="selection" width="55" align="center" v-if="isBatch">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                 <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDelete(row,$index)"  v-if="!row.state || row.state !== -1 " title="删除">
                                                <img src="@/assets/btn/cancelDelete.png" class="cancel_delete"
                                                    @click="singleCancelDelete(row)"
                                                        v-if="row.state === -1 && row.leasePlanDtlId"
                                                    title="取消删除"
                                                />
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="equipmentName" label="设备名称" min-width="200" show-overflow-tooltip align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    width="200"
                                    align="center"
                                >
                                     <template slot-scope="{ row }">
                                        <span v-if="leaseTypeList[formData.leaseType].label !=='临租'">{{row.specificationModel}}</span>
                                        <el-input v-else v-model="row.specificationModel" clearable @input="curStateChange(row)"></el-input>
                                     </template>
                                </el-table-column>
                                <el-table-column prop="changeTimeUnit" width="200">
                                    <template slot="header">
                                        <div class="tab-header">变更后计时单位<span class="tab-heade-icon">变</span></div>
                                    </template>
                                     <template slot-scope="{ row }">
                                        <span v-if="leaseTypeList[formData.leaseType].label !=='临租'">{{row.changeTimeUnit}}</span>
                                        <el-select
                                            v-else
                                            v-model="row.changeTimeUnit"
                                            placeholder="请选择"
                                            @input="curStateChange(row)"
                                        >
                                            <el-option
                                                v-for="(
                                                    item
                                                ) in timeUnitList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.label"
                                            >
                                            </el-option>
                                        </el-select>
                                     </template>
                                </el-table-column>
                                <el-table-column prop="changeQuantity" width="150" align="right">
                                    <template slot="header">
                                        <div class="tab-header">变更后租赁数量<span class="tab-heade-icon">变</span></div>
                                    </template>
                                    <template slot-scope="{ row }">
                                        <el-input v-model.number="row.changeQuantity" clearable @input="curStateChange(row)"
                                        v-enter-integer1="{
                                            set: row,
                                            key: 'changeQuantity'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changePrice" width="200" align="right">
                                     <template slot="header">
                                        <div class="tab-header">变更后单价（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.changePrice" clearable @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'changePrice'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeEnterExitCost" width="230" align="right">
                                     <template slot="header">
                                        <div class="tab-header">变更后预计进退场费用（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.changeEnterExitCost" clearable @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'changeEnterExitCost'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeServiceTime" width="170">
                                    <template slot="header">
                                        <div class="tab-header">变更后预计使用时间<span class="tab-heade-icon">变</span></div>
                                    </template>
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.changeServiceTime" clearable @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'changeServiceTime'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeAmount" width="200" align="right">
                                     <template slot="header">
                                        <div class="tab-header">变更后金额（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeEnterDate" width="200">
                                     <template slot="header">
                                        <div class="tab-header">变更后预计进场时间<span class="tab-heade-icon">变</span></div>
                                    </template>
                                    <template slot-scope="{ row }">
                                        <el-date-picker type="date" placeholder="选择日期" v-model="row.changeEnterDate" style="width: 100%;" value-format="yyyy-MM-dd"
                                        @input="curStateChange(row)"></el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="原租赁单价（元）"
                                    width="150"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="原租赁数量"
                                    width="150"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="原计时单位"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                               <el-table-column
                                    prop="enterExitCost"
                                    label="原预计进退场费（元）"
                                    width="180"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="原预计金额（元）"
                                    width="150"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.amount}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="enterDate"
                                    label="原预计进场时间"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="serviceTime"
                                    label="原预计使用时间"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="facilityplan" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="50121"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.state" @exas="exas" :founderId="formData.founderId" />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { hideLoading, formatDate } from '@/utils/common'
import requestAudit from '@/api/equip/common.js'
//import ComExaButtons from '@/components/common/exaButtons'
import request from '@/api/equip/equipPlan.js'
import count from '@/api/equip/equipPlanCount.js'
import { selectConfigPlanEquip, selectEquipmentBase } from '@/api/equip/popupCallback.js'
import { exas, saveAll, submitCommit } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            isBatch: true, //是否进入批量操作
            batch: '进入批量管理',
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                'share': '',
                'auditCost': 0,
                'auditTime': '',
                'auditor': '',
                'auditorId': '',
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'baseCurTotalCost': 0,
                'billDate': '',
                'billId': '',
                'billNo': '',
                'changeBillId': '',
                'changeBillNo': '',
                'changeState': 0,
                'changeTotalCost': 0,
                'configurationPlanId': '',
                'configurationPlanNo': '',
                'currency': '',
                'currencyId': '',
                'esaId': '',
                'founderId': '',
                'founderName': '',
                'isExcss': 0,
                'isTemporaryLease': '',
                'leaseType': '2',
                'modifier': '',
                'modifierId': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'number': 0,
                'orgId': '',
                'orgName': '',
                'recorder': '',
                'recorderId': '',
                'remarks': '',
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'rmbSumTotalCost': 0,
                'settleAmount': 0,
                'source': '',
                'state': 0,
                'totalCost': 0,
                'version': 0,
                'workId': ''
            },
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 50121,  //配置计划
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 50121,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            billid: this.$route.query.billid,
            planConfigurationDtlList: [], //计划明细
            planConfigurationDtlListCopy: [],
            delBeforeList: [], //删除前的明细
            planSelect: [], //计划明细选择项
            auditHistoryTable: [],
            currentRow: {},
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            planConfigurationDtlListA: [],
            isFontColor: null,
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
            leaseTypeList: state => state.equip.equipData.leaseTypeList, //租赁类型
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>+x.value === param)
                if(obj !== undefined) {
                    return obj.label
                }
            }
        },
        //当前单据状态
        state () {
            return this.formData.state
        },
        //传输财务共享
        shareLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        //ComExaButtons
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.getDicValue()
    },
    mounted () {
        this.init()  //初始化所有数据
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations([ 'setAuditParams']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        batchOperation () {
            this.isBatch = !this.isBatch
            if(this.isBatch) {
                this.batch = '退出批量管理'
                this.$refs.planTable.clearSelection()
            }else{
                this.batch = '进入批量管理'
            }
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //传输财务共享字体颜色  未传，返回修改 红色   财务共享审核中，已传 绿色
        shareFontColor () {
            if(this.formData.share === 0 || this.formData.share === 1) {
                this.isFontColor = true
            }else{
                this.isFontColor = false
            }
        },
        //初始化所有数据
        init () {
            Promise.all([
                this.getInfo(),
                //this.getPlanList(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            requestAudit.history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //基础信息查询
        getInfo () {
            request.getLeaseBaseInfoChange(this.billid).then(res=>{
                this.formData = res
                this.shareFontColor()
                this.getPlanList()
            })
        },
        //计划明细查询
        getPlanList () {
            request.getleaseDetailsChange(this.billid).then(res=>{
                this.planConfigurationDtlListCopy = []
                this.planConfigurationDtlList = res
                res.map(item=>{
                    this.planConfigurationDtlListCopy.push(item)
                    this.onAmount(item)
                })
            })
        },
        //修改基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                request.updateleaseBaseInfoChange(this.formData).then(()=>{
                    this.verifyTable().then(()=>{
                        request.updateleasePlanChange(this.planConfigurationDtlList).then(()=>{
                            resolve()
                        }).catch(err=>{
                            this.setError('planDetail')
                            reject(err)
                            this.scorllError()
                        })
                    }).catch(err=>{
                        this.setError('planDetail')
                        reject(err)
                        this.scorllError()
                    })

                }).catch(err=>{
                    this.setError('baseInfo')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        /*明细 */
        //修改行样式
        tableRowClass ({ row }) {
            if(row.state == -1) {
                if(row.leasePlanDtlId) {
                    return 'red'
                }else{
                    return  'row-hide'
                }
            }else if(row.state == 1) {
                return 'green'
            }else if(row.state == 2) {
                return 'yellow'
            }
            return ''
        },
        //选择设备基础库
        selectEquip () {
            let json = {
                'categoryId': '00000',
                'isUpdate': false,
                'keyword': ''
            }
            selectEquipmentBase(json).then(res=>{
                res.forEach(item=>{
                    let obj = {
                        'changeServiceTime': null,
                        'acceptedQuantity': 0,
                        'amount': 0,
                        'auditAmount': 0,
                        'auditEnterExitCost': 0,
                        'auditPrice': 0,
                        'auditQuantity': 0,
                        'auditUseTime': 0,
                        'billId': this.billid,
                        'billNo': '',
                        'changeAmount': null,
                        'changeEnterDate': '',
                        'changeEnterExitCost': null,
                        'changeFacilityPlanLeaseDtlId': '',
                        'changeNewOldRate': null,
                        'changePrice': null,
                        'changeQuantity': null,
                        'changeTimeUnit': '',
                        'changeType': 1,
                        'enterDate': '',
                        'enterExitCost': 0,
                        'equipmentId': '',
                        'equipmentName': '',
                        'isUsed': '',
                        'leasePlanDtlId': '',
                        'mark': false,
                        'newOldRate': 0,
                        'oldState': 0,
                        'oneLevelCategoryId': '',
                        'oneLevelCategoryName': '',
                        'price': 0,
                        'quantity': 0,
                        'rentalRemark': '',
                        'rentalUnit': '',
                        'rmbSumCost': 0,
                        'scSumCost': 0,
                        'serviceTime': 0,
                        'specificationModel': '',
                        'state': 1,
                        'timeUnit': '',
                        'unit': '',
                        ...item
                    }
                    obj.state = 1
                    this.planConfigurationDtlListCopy.push(obj)
                    this.planConfigurationDtlList.push(obj)
                })
            })
        },
        //选择配置计划设备
        selectConfigEquip () {
            let ids = []
            ids = this.planConfigurationDtlListCopy.map(x=>x.configurationPlanDtlId)
            // ids = this.planConfigurationDtlListCopy.map(x=>{
            //     if(x.state !== -1) {
            //         return x.configurationPlanDtlId
            //     }
            // })
            let json = {
                'configId': this.formData.configurationPlanId,
                ids: ids
            }
            selectConfigPlanEquip(json).then(res=>{
                res.forEach(item=>{
                    item.billId = this.billid
                    item.changeType = 1
                    item.state = 1
                    item.enterDate = formatDate(item.item, 'yyyy-MM-dd')
                    let obj =  {
                        'changeServiceTime': null,
                        'acceptedQuantity': null,
                        'amount': null,
                        'auditAmount': null,
                        'auditEnterExitCost': null,
                        'auditPrice': null,
                        'auditQuantity': null,
                        'auditUseTime': null,
                        'billId': '',
                        'billNo': '',
                        'changeAmount': null,
                        'changeEnterDate': '',
                        'changeEnterExitCost': null,
                        'changeFacilityPlanLeaseDtlId': '',
                        'changeNewOldRate': null,
                        'changePrice': null,
                        'changeQuantity': null,
                        'changeTimeUnit': '',
                        'changeType': 1,
                        'enterDate': '',
                        'enterExitCost': 0,
                        'equipmentId': '',
                        'equipmentName': '',
                        'isUsed': '',
                        'leasePlanDtlId': '',
                        'mark': false,
                        'newOldRate': null,
                        'oldState': null,
                        'oneLevelCategoryId': '',
                        'oneLevelCategoryName': '',
                        'price': null,
                        'quantity': null,
                        'rentalRemark': '',
                        'rentalUnit': '',
                        'rmbSumCost': null,
                        'scSumCost': null,
                        'serviceTime': null,
                        'specificationModel': '',
                        'state': 1,
                        'timeUnit': '',
                        'unit': '',
                        'configurationPlanDtlId': item.configurationPlanDtlId,
                        ...item
                    }
                    obj.isNewAdd = true //判断是否是新增的数据
                    this.planConfigurationDtlList.push(obj)
                    this.planConfigurationDtlListCopy.push(obj)
                })
                this.itemObj = {}
                this.itemObjCopy = {}
                this.planConfigurationDtlListCopy = this.planConfigurationDtlListCopy.reduce((item, next)=>{
                    if(!this.itemObjCopy[next.configurationPlanDtlId]) {
                        item.push(next)
                        this.itemObjCopy[next.configurationPlanDtlId] = true
                    }
                    return item
                }, [])
                this.planConfigurationDtlList = this.planConfigurationDtlList.reduce((item, next)=>{
                    if(next.changeType == -1) {
                        item.push(next)
                    }else{
                        if(!this.itemObj[next.configurationPlanDtlId]) {
                            item.push(next)
                            this.itemObj[next.configurationPlanDtlId] = true
                        }
                    }
                    return item
                }, [])
            })
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.currentRow = row
            if(row.state != -1) {
                if(row.leasePlanDtlId === '' || row.leasePlanDtlId === null) {
                    this.currentRow.changeType = 2
                    this.currentRow.state = 1
                }else{
                    this.currentRow.changeType = 2
                    this.currentRow.state = 2
                }
                this.onAmount(row)
            }
        },
        //计算金额 = 金额 = 数量*单价*预计使用时间+预计进退场费
        onAmount  (row) {
            row.changeAmount = count.onChangeLeaseAmount(row.changeQuantity, row.changePrice, row.changeServiceTime,  row.changeEnterExitCost)
            this.onUpCollect()
        },
        //费用合计 = 明细获取金额向上汇总
        onUpCollect () {
            this.formData.changeTotalCost = null
            this.formData.changeTotalCost = count.onChangeLeaseUpCollect(this.planConfigurationDtlList)
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //单个删除计划明细
        handleDelete (row, $index) {
            row.oldState = row.state  //存删除之前的状态
            let length = this.errorMsg.length
            if(row.mark) {
                this.clientPop(
                    'info',
                    `${row.equipmentName}设备已被其他单据引用，不能删除！`,
                )
            }else{
                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    ()=>{
                        if(row.leasePlanDtlId) {
                            this.$set(this.planConfigurationDtlList[$index], 'changeType', -1)
                            this.$set(this.planConfigurationDtlList[$index], 'state', -1)
                            if(!row.leasePlanDtlId) {
                                this.planConfigurationDtlListCopy.splice($index, 1)
                            }
                            if (length > 0 ) {
                                this.verifyTable()
                            }
                            this.onUpCollect()
                        }else{
                            this.planConfigurationDtlList.splice($index, 1)
                            this.planConfigurationDtlListCopy.splice($index, 1)
                            this.onUpCollect()
                            if (length > 0 ) {
                                this.verifyTable()
                            }
                        }
                    }
                )

            }
        },
        //点击删除弹窗
        deletePlanList () {
            const length = this.planSelect.length
            if(length > 0) {
                this.mark = this.planSelect.find(x=>{  //判断是否被引用
                    if(x.mark === true) {
                        return true
                    }
                })
            }
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else if(this.mark) {
                this.clientPop(
                    'info',
                    `${this.mark.equipmentName}设备已被其他单据引用，不能删除！`,
                    this.$refs.planTable.clearSelection()
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.delete
                )
            }
        },
        //批量删除计划明细
        delete () {
            this.existDelBeforeList()
            let length = this.errorMsg.length
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item=>{
                    if(item.leasePlanDtlId) {
                        this.$set(item, 'changeType', -1)
                        this.$set(item, 'state', -1)
                        for(let i = this.planConfigurationDtlListCopy.length; i > 0; i--) {
                            if(this.planConfigurationDtlListCopy[i - 1] === item) {
                                if(!this.planConfigurationDtlListCopy[i - 1].configurationPlanDtlId) {
                                    this.planConfigurationDtlListCopy.splice(i - 1, 1)
                                }

                            }
                        }
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                        this.$refs.planTable.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.planConfigurationDtlList.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.leasePlanDtlId[i - 1] === localArr[j]) {
                                    this.planConfigurationDtlList.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                                if(this.planConfigurationDtlListCopy[i - 1] === localArr[j]) {
                                    this.planConfigurationDtlListCopy.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                            }
                        }
                        this.$refs.planTable.clearSelection()
                    }
                })
            }
        },
        //取消删除
        cancelDelete () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择删除的数据,请选择!',
                )
            }else{
                this.planSelect.forEach(item=>{
                    if(item.changeFacilityPlanLeaseDtlId !== '' && item.state === -1) {
                        this.planConfigurationDtlList.forEach(x=>{
                            if(x.changeFacilityPlanLeaseDtlId === item.changeFacilityPlanLeaseDtlId) {
                                if(x.leasePlanDtlId) {
                                    x.state = 2
                                    x.changeType = 2
                                }
                            }
                        })
                    }

                })
                this.onUpCollect()
                this.$refs.planTable.clearSelection()
            }
        },
        //单个取消删除
        singleCancelDelete (row) {
            row.state = 2
            row.changeType = 2
            this.onUpCollect()
        },
        //存删除之前的计划明细的状态
        existDelBeforeList () {
            this.planSelect.forEach(item=>{
                let obj = this.planConfigurationDtlList.find(x=>x.changeFacilityPlanLeaseDtlId === item.changeFacilityPlanLeaseDtlId)
                obj.oldState = obj.state
            })
        },
        //取消
        handleClose  () {
            this.$router.replace('/leasePlanList')
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.planConfigurationDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if(item.changeTimeUnit === null || item.changeTimeUnit === '') {
                            let str = `请选择第 ${index + 1} 行的（变更后计时单位）`
                            this.errorMsg.push(str)
                        }
                        if(item.changeQuantity === null || item.changeQuantity === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后租赁数量）`
                            this.errorMsg.push(str)
                        }
                        if(item.changePrice === null || item.changePrice === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后单价）`
                            this.errorMsg.push(str)
                        }
                        if(item.changeEnterExitCost === null || item.changeEnterExitCost === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后预计进退场费）`
                            this.errorMsg.push(str)
                        }
                        if(item.changeServiceTime === null || item.changeServiceTime === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后预计使用时间）`
                            this.errorMsg.push(str)
                        }
                        if( item.changeEnterDate === null || item.changeEnterDate === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后预计进场时间）`
                            this.errorMsg.push(str)
                        }
                    }

                })
                if(this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                }else{
                    this.isErrorMsg = false
                    resolve()
                }

            })

        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo()
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo()
                ]
            }
            submitCommit(this, requestFn, 0)
        },
        //删除单据
        deleteBills () {
            let billids = [this.billid]
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    request.deleteLeaseChangeHistoy(billids).then(()=>{
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                }
            )
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 0)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
    .e-table {
    background: #fff;
}
</style>
